<template>
  <div class="tw-libwscontroller"
    :class="{[`x${this._uid}`]:true}">
    <ul class="tw-wscontroller" v-show="data.length>0">
      <li class="tw-wscontroller-item"
        :class="{xactive: index===curIndex}"
        v-for="(item,index) in data"
        :key="index"
        @click="curIndex=index;wsSend(item.href);"
      >
        <img v-if="item.imgUrl" class="xicon" :src="item.imgUrl" />
        <img v-else-if="icons[index]" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[index].localPath}`" />
        <img src="@assets/index.png" class="xicon" v-else>
        <div :titie="item.name" class="xname">
          {{item.name}}
        </div>
      </li>
    </ul>
    <tw-lib-nodata v-show="data.length===0" />
  </div>
</template>

<script>
import props from './props'
import nodata from '../tw-lib-base/no-data/no-data'

export default {
  name: 'websock-controller',

  mixins: [nodata],

  props,

  data() {
    return {
      timeoutObj: null,
      curIndex: '',
      ws: null
    }
  },

  computed: {
    style () {
      return {
        fontSize: this.fontSize,
        background: this.bgColor,
        color: this.color,
        activeColor: this.activeColor,
        activeBorder: this.activeBorder,
        textPadding: this.textPadding,
        lineHeight: this.lineHeight,
        itemPadding: this.itemPadding,
        marginLeft: this.marginLeft,
        marginTop: this.marginTop,
        width: this.width,
        itemBorder: this.itemBorder,
        itemBorderRadius: this.itemBorderRadius,
        padding: this.padding
      }
    }
  },

  methods: {
    setStyle () {
      const style = `
        ::root.tw-libwscontroller .tw-wscontroller {
          padding: ${this.padding};
        }

        ::root.tw-libwscontroller .tw-wscontroller-item {
          border-radius: ${this.itemBorderRadius};
          border: ${this.itemBorder};
          width: ${this.width};
          margin-bottom: ${this.marginTop};
          margin-right: ${this.marginLeft};
          background-color: ${this.bgColor};
          padding: ${this.itemPadding};
          box-shadow: ${this.boxshadow};
        }

        ::root.tw-libwscontroller .tw-wscontroller-item .xname {
          line-height: ${this.lineHeight};
          padding: ${this.textPadding};
          font-size: ${this.fontSize};
          color: ${this.color};
        }

        ::root.tw-libwscontroller .tw-wscontroller-item.xactive {
          border: ${this.activeBorder};
          box-shadow: ${this.activeBoxshadow};
        }

        ::root.tw-libwscontroller .tw-wscontroller-item.xactive .xname {
          color: ${this.activeColor};
        }

      `
      this.addStyle(style)
    },

    addStyle (style) {
      this.$el.classList.add(`x${this._uid}`)
      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/::root/gm, `.x${this._uid}`).replace(/\n/gm, '')

      document.head.appendChild(styleEl)
    },

    wsSend (msg) {
      if (this.useClickfn && typeof this.clickFn === 'function') {
        this.clickFn(msg, this)
      } else {
        this.ws.send(msg)
      }
    },
    /**
     * 链接websocket服务器
     */
    initWebsoket () {
      this.ws = new WebSocket(this.wsLink)
      let vm = this
      this.ws.onopen = function () {
        console.log('%c App connects to wsServer success.', 'color: green')
        vm.wsKeepConnect()
      }
      // this.ws.onmessage = function (e) {
      //   vm.wsReset()
      //   console.log('from server: ' + e.data)
      //   // 排除控制器页面
      //   if (e.data) {
      //     vm.$router.push(e.data)
      //   }
      // }
    },
    /**
     * 保持连接
     */
    wsKeepConnect () {
      let vm = this
      this.timeoutObj = setInterval(() => {
        if (vm.ws.readyState === 1) {
          // '请勿修改 HeartBeat 一词'
          vm.ws.send('HeartBeat')
        }
      }, vm.timeout)
    },
    /**
     * 重置心跳确认包
     */
    wsReset () {
      clearInterval(this.timeoutObj)
      this.wsKeepConnect()
    },
  },
  beforeDestroy () {
    if (this.ws) {
      this.ws.close()
    }
    if (this.timeoutObj) {
      window.clearInterval(this.timeoutObj)
    }
  },

  mounted () {
    this.setStyle()
    this.initWebsoket()
  },

  watch: {
    timeout () {
      if (this.ws) {
        this.ws.close()
      }
      if (this.timeoutObj) {
        window.clearInterval(this.timeoutObj)
      }
      this.initWebsoket()
    },

    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
